import axios, { AxiosError, AxiosResponse } from 'axios'
import { HttpMessage } from '../httpStatus'
import { getToken } from './token'

// 假设这是你自定义的 ApiResponse 类型
interface ApiResponse<T> extends AxiosResponse {
  data: T
  message: string
  success: boolean
}

const request = axios.create({
  baseURL: '/api',
  timeout: 120000 // 两分钟
})

const whiteList = ['/login', '/api/auth/code', '/api/auth/login']

// 请求拦截器
request.interceptors.request.use(
  config => {
    console.log('请求拦截器', config.url)
    if (whiteList.includes(config.url!)) {
      return config
    }

    // 从 cookie 获取 token
    const token = getToken()

    // 如果有 token 则添加到请求头
    if (token) {
      config.headers.Authorization = token
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse): Promise<ApiResponse<any>> => {
    // 手动转换为 ApiResponse 类型
    const apiResponse: ApiResponse<any> = {
      ...response,
      data: response.data.data,
      message: response.data.message,
      success: response.data.success
    }
    return Promise.resolve(apiResponse)
  },
  (error: AxiosError) => {
    // 请求失败（网络错误等）
    // 如果后端返回了错误信息，则直接抛出去
    if (error.response?.data) {
      const errorData = error.response.data as { message: string }
      return Promise.reject(errorData.message)
    } else {
      // 如果后端没有返回错误信息，则根据 HTTP 状态码返回错误信息
      const status = error.response?.status as keyof typeof HttpMessage
      const msg = status && status in HttpMessage ? HttpMessage[status] : ('网络错误' as string)
      return Promise.reject(msg)
    }
  }
)

export default request
